package com.chinawayltd.ews.sample.web.materiel;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.TMateriel;
import com.chinawayltd.ews.sample.model.TOrderDetail;
import com.chinawayltd.ews.sample.model.materiel.MaterielVO;
import com.chinawayltd.ews.sample.service.common.CommonService;
import com.chinawayltd.ews.sample.service.materiel.MaterielService;
import com.chinawayltd.ews.sample.service.order.OrderService;
import com.chinawayltd.ews.sample.util.BaseController;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.util.excel.ExcelGenerateModel;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExcelUtils;
import com.chinawayltd.ews.sample.web.query.LogGirdQuery;
import com.chinawayltd.ews.sample.web.query.MaterielGirdQuery;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description 物料信息Controller
 * @author: chenxin
 * @create: 2018年4月16日 下午3:44:06
 */
@Api(tags = { "物料信息管理API" })
@RestController
@RequestMapping(value = "/web/meteriel")
public class MaterielController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MaterielService materielService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CommonService commonService;

    @ApiOperation(value = "物料信息列表查询接口")
    @RequestMapping(value = "/loadGirdData", method = { RequestMethod.POST })
    public ResultModel loadGirdData(MaterielGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        try {
            List<MaterielVO> MaterielList = materielService.listMaterielByPage(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", MaterielList));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("result", null));
            logger.error("物料列表查询出错！", e);
        }
        return model;
    }

    @ApiOperation(value = "根据ID查询单个物料信息")
    @RequestMapping(value = "/find/{id}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "id", value = "物料ID", dataType = "Long", required = true)
    public ResultModel getMaterielById(@PathVariable Long id) {
    	ResultModel model = new ResultModel();
    	try {
			TMateriel data = materielService.getMaterielById(id);
			model.setData(new JSONObject().fluentPut("result" , data));
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("result", null));
        	logger.error("根据ID查询物料信息出错！id：" + id, e);
        }
        return model;
    }

    @ApiOperation(value = "新增物料信息")
    @RequestMapping(value = "/add", method = { RequestMethod.POST })
	@ApiImplicitParams({
    	@ApiImplicitParam(paramType="query", name="materielNo",value="物料编码",dataType="String"),
    	@ApiImplicitParam(paramType="query", name="materielName",value="物料名称",dataType="String"),
    	@ApiImplicitParam(paramType="query", name="materielVolume",value="物料体积",dataType="Long")
    })
    public ResultModel addMateriel(TMateriel tMateriel) {
    	ResultModel model = new ResultModel();
		try {
			if(StringUtils.isBlank(tMateriel.getMaterielNo())){
				throw new BusinessException("编号不能为空，添加失败!");
			}
			if(StringUtils.isBlank(tMateriel.getMaterielVolume().toString())){
				throw new BusinessException("体积不能为空，添加失败!");
			}
			if(StringUtils.isBlank(tMateriel.getMaterielName().toString())){
				throw new BusinessException("名称不能为空，添加失败!");
			}
			List<TMateriel> list = materielService.getMaterleiByIdOrCode(null, tMateriel.getMaterielNo().trim());
			if (list.size() > 0) {
				throw new BusinessException("物料编号已存在，添加失败!");
			}
			int result = materielService.insertMateriel(tMateriel);
			if (result > 0) {
				model.setData(new JSONObject().fluentPut("result", "添加成功"));
			} else {
				model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg", "添加失败"));
			}
        } catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
        } catch (Exception e){
        	model.setSub_code(1);
        	model.setData(new JSONObject().fluentPut("sub_msg" , "添加异常"));
        	logger.error("新增物料时发生异常！", e);
        }
		return model;
    }

    @ApiOperation(value = "修改物料信息")
    @RequestMapping(value = "/update", method = { RequestMethod.POST })
    @ApiImplicitParams({
    	@ApiImplicitParam(paramType="query", name="id",value="物料id",dataType="String"),
    	@ApiImplicitParam(paramType="query", name="materielNo",value="物料编码",dataType="String"),
    	@ApiImplicitParam(paramType="query", name="materielName",value="物料名称",dataType="String"),
    	@ApiImplicitParam(paramType="query", name="materielVolume",value="物料体积",dataType="Long")
    })
    public ResultModel updateMateriel(TMateriel tMateriel) {
    	ResultModel model = new ResultModel();
		try {
			if(StringUtils.isBlank(tMateriel.getId().toString())){
				throw new BusinessException("ID不能为空，修改失败!");
			}
			if(StringUtils.isBlank(tMateriel.getMaterielNo())){
				throw new BusinessException("编号不能为空，修改失败!");
			}
			if(StringUtils.isBlank(tMateriel.getMaterielVolume().toString())){
				throw new BusinessException("体积不能为空，修改失败!");
			}
			if(StringUtils.isBlank(tMateriel.getMaterielName().toString())){
				throw new BusinessException("名称不能为空，修改失败!");
			}
			List<TMateriel> list = materielService.getMaterleiByIdOrCode(tMateriel.getId(), tMateriel.getMaterielNo());
			if (list.size() > 0) {
				throw new BusinessException("物料编号已存在，修改失败!");
			}
			int result = materielService.updateMateriel(tMateriel);
			if (result > 0) {
				model.setData(new JSONObject().fluentPut("result", "修改成功"));
			} else {
				model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg", "修改失败"));
			}
        } catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
        } catch (Exception e){
        	model.setSub_code(1);
        	model.setData(new JSONObject().fluentPut("sub_msg" , "修改异常"));
        	logger.error("司机排班信息修改发生异常！"+e);
        }
		return model;
    }

	@ApiOperation(value = "通过材料编号查询对象,可用来校验编号唯一性", notes = "校验名称：校验添加编号不需要ID,校验编号的修改必要ID,返回可用和不可用!")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "id", value = "材料id", dataType = "Long", required = false),
		@ApiImplicitParam(paramType = "query", name = "name", value = "材料编号", dataType = "String", required = true)})
	@RequestMapping(value = { "/getMaterleiByIdOrCode" }, method = RequestMethod.POST)
	public ResultModel getMaterleiByIdOrCode(Long id, String name){
		ResultModel model = new ResultModel();
		try {
			List<TMateriel> list = materielService.getMaterleiByIdOrCode(id, name);
			if(list !=null && list.size() > 0){
				model.setData(new JSONObject().fluentPut("result" , "已存在"));
			}else{
				model.setData(new JSONObject().fluentPut("result" , "可用"));
			}
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询失败"));
		}
		return model;
	}
    @ApiOperation(value = "删除物料信息")
    @RequestMapping(value = "/delete/{id}", method = { RequestMethod.DELETE })
    @ApiImplicitParam(paramType = "path", name = "id", value = "物料信息ID", dataType = "Long", required = true)
    public ResultModel deleteMaterielById(@PathVariable Long id) {
    	ResultModel model = new ResultModel();
        try {
        	List<TOrderDetail> list = orderService.listOrderDetailByMaterielId(id);
    		if (list.size() > 0) {
    			model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg", "订单明细含有此物料，删除失败！"));
    		}else{
    			int result = materielService.deleteMaterielById(id);
            	if (result > 0) {
    				model.setData(new JSONObject().fluentPut("result", "删除成功"));
    			} else {
    				model.setSub_code(1);
    				model.setData(new JSONObject().fluentPut("sub_msg", "删除失败"));
    			}
    		}
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "删除失败"));
        	logger.error("根据ID删除信息出错！id：" + id, e);
        }
		return model;
    }
    
    @ApiOperation(value = "物料信息管理导出接口")
    @RequestMapping(value = "/exportGirdData", method = { RequestMethod.POST })
    public void exportGirdData(@RequestBody MaterielGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<MaterielVO> materielList = materielService.listMaterielByPage(queryParam);
            //List<Map<String, Object>> materielList = materielService.exportGirdData(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(materielList)
                    .cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "物料信息管理列表" , request, response);
        }catch (Exception e){
            logger.error("物料信息管理列表导出出错！", e);
        }
    }
    
    /**
	 * 解析excel2003和2007的数据，并导入到数据库，错误数据导出到前台
	 * @author: chenxin
	 * @date: 2018年4月26日
	 * @param file
	 * @param request
	 * @param response
	 */
    @SuppressWarnings("rawtypes")
    @ApiOperation(value = "物料基础信息批量导入")
	@RequestMapping(value="/readExcel", method = { RequestMethod.POST })
    public Object readExcel(@RequestParam("file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
    	JSONObject object = new JSONObject();
    	try {
    		// 1、解析导入的数据
	    	ExcelObjModel model = ExcelUtils.readExcel(file);
	    	if(model.getCode() !=0){
	    		object.put("state", 400);
		    	object.put("msg", model.getMsg());
				return object.toString();
			}
			// 2、导入数据到数据库
			List<PageData> list = (List)model.getList();
			if(list ==null || list.isEmpty()){
				object.put("state", 400);
		    	object.put("msg", "导入的表不是有效的文件或数据为空");
		    	return object.toString();
			}
			ExcelObjModel result = materielService.insertList(list);
			// 3、导出错误数据
			if(result.getList().size() > 0){
		        ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(result.getList()).cloumnList(result.getCloums()).build();
		        Workbook workbook = ExcelUtils.generateExcel(excelModel);
				this.sendWorkbook(workbook, "物料基础信息" , request, response);
			}
		} catch (BusinessException e) {
		 	object.put("state", 400);
	    	object.put("msg", e.getMessage());
	    	return object.toString();
		} catch (IOException e) {
			object.put("state", 400);
	    	object.put("msg", "导入数据接口出错");
	    	return object.toString();
		} catch (Exception e) {
			logger.error("导入数据接口出错！", e);
		}
    	return null;
    }
    
    
    @ApiOperation(value = "通过ID查询操作日记接口,需要传id")
    @RequestMapping(value = "/getLogDataById", method = { RequestMethod.POST })
    public ResultModel getLogDataById(LogGirdQuery queryParam) {
		ResultModel model = new ResultModel();
		try {
			queryParam.setTableName("T_MATERIEL");
            List<TLog> list = commonService.getLogDataById(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", null));
            logger.error("通过ID查询操作日记接口异常！", e);
        }
        return model;
    }
}
